package com.project.dhCamera.handler;

import com.project.dhCamera.utils.ProgramConfig;
import com.project.dhCamera.entity.CommandTasker;
import com.project.dhCamera.service.OutHandlerMethod;
import com.project.dhCamera.utils.ExecUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Sweey Zhang
 * @description
 * @date 2021/7/20 12:08
 */
@Component
public class TaskHandlerImpl implements TaskHandler{
    @Autowired
    private ProgramConfig config;
    @Autowired
    private OutHandlerMethod ohm;


    public void setOhm(OutHandlerMethod ohm) {
        this.ohm = ohm;
    }

    @Override
    public CommandTasker process(String id, String command) {
        CommandTasker tasker = null;
        try {
            tasker = ExecUtil.createTasker(id,command,ohm);

            if(config.isDebug()) {
                System.out.println(id+" 执行命令行："+command);
            }

            return tasker;
        } catch (IOException e) {
            //运行失败，停止任务
            ExecUtil.stop(tasker);

            if(config.isDebug()) {
                System.err.println(id+" 执行命令失败！进程和输出线程已停止");
            }

            // 出现异常说明开启失败，返回null
            return null;
        }
    }

    @Override
    public boolean stop(Process process) {
        return ExecUtil.stop(process);
    }

    @Override
    public boolean stop(Thread outHandler) {
        return ExecUtil.stop(outHandler);
    }

    @Override
    public boolean stop(Process process, Thread thread) {
        boolean ret=false;
        ret=stop(thread);
        ret=stop(process);
        return ret;
    }
}
